﻿/*
 * timedmeasuremonitor.cpp
 *
 *  Created on: 2017年4月15日
 *      Author: work
 */

#include <dm/export.hpp>

#define DM_API_SCADA DM_API_EXPORT

#include <dm/scada/timedmeasuremonitor.hpp>
#include <dm/scada/timedmeasuremgr.hpp>
#include <dm/scada/measuremgr.hpp>

#include <dm/datetime.hpp>

#include <iostream>

using namespace std;

namespace dm{
namespace scada{

CTimedMeasureMonitor::CTimedMeasureMonitor():m_mgr(CTimedMeasureMgr::ins()),m_p(CTimedMeasureMgr::ins().m_q->getCurPos()){
}

CTimedMeasureMonitor::CTimedMeasureMonitor( const ringpos_t* p ):m_mgr(CTimedMeasureMgr::ins()){
	m_p = *p;
}

CTimedMeasureMonitor::~CTimedMeasureMonitor(){
}

void CTimedMeasureMonitor::onNew( const ringpos_t& pos,const CTimedMeasure& info,const bool& overFlow )const{
	const dm::CTimeStamp& ts = info.getTimeStamp();
	dm::CDateTime dt(ts);
	cout <<pos.getCycle()<<"."<<pos.getPos() <<" ["<<ts.seconds()<<'.'<<ts.mseconds()<<' '<<dt.toString().c_str()<<"] ";
	if( overFlow )
		cout <<"(of)";

	CMeasureMgr& mgr = CMeasureMgr::ins();
	cout << mgr.desc(info.getIndex()) <<"(id="<<mgr.id(info.getIndex())<<",name="<<mgr.name(info.getIndex())<<") "<<info.getValue()
			<<endl;
}

bool CTimedMeasureMonitor::filter( const ringpos_t& /*pos*/,const CTimedMeasure& /*info*/,const bool& /*overflow*/ )const{
	return false;
}

void CTimedMeasureMonitor::run(){
	CTimedMeasure info;
	bool overflow;

	while( true ){
		if(m_mgr.m_q->waitAndCheckOver(m_p,overflow,info,1))
			continue;
		if( !filter(m_p,info,overflow) )
			onNew(m_p,info,overflow);
		if( overflow )
			m_p = m_mgr.m_q->getCurPos();
	}
}

bool CTimedMeasureMonitor::tryGet( CTimedMeasure& info,bool& overflow ){
	return m_mgr.m_q->popAndCheckOver( m_p,overflow,info);
}

void CTimedMeasureMonitor::get( CTimedMeasure& info,bool& overflow ){
	m_mgr.m_q->waitAndCheckOver( m_p,overflow,info);
}

void CTimedMeasureMonitor::reset(){
	m_p = m_mgr.m_q->getCurPos();
}

}
}
